package com.SouthernWall_404.age_tool.common.command;

import com.mojang.brigadier.Command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.level.Level;

public class ChestLootCommand {
    public static void register(CommandDispatcher<CommandSourceStack> commandDispatcher, boolean bl) {
        commandDispatcher.register(Commands.literal("age_tool")
//                .requires(commandSourceStack -> commandSourceStack.hasPermission(0))
                .then(Commands.literal("chestloot")
                        .then(Commands.literal("get")
                                .executes(ChestLootCommand::handler))));
    }

    private static int handler(CommandContext<CommandSourceStack> context)throws CommandSyntaxException
    {

        Player player = context.getSource().getPlayer();
        Level level = context.getSource().getLevel();

        if (!level.isClientSide() && player != null) {
            // 射线追踪
            Vec3 eyePos = player.getEyePosition();
            Vec3 lookVec = player.getLookAngle();
            Vec3 endPos = eyePos.add(lookVec.scale(100));
            BlockHitResult hitResult = level.clip(
                    new ClipContext(eyePos, endPos,
                            ClipContext.Block.OUTLINE,
                            ClipContext.Fluid.NONE,
                            player)
            );

            if (hitResult.getType() == HitResult.Type.BLOCK) {
                BlockPos pos = hitResult.getBlockPos();
                BlockState state = level.getBlockState(pos);
                player.sendSystemMessage(Component.literal("目标方块: " + state.getBlock().getName()));
            }
        }
        return Command.SINGLE_SUCCESS;
    }
}
